import { Component, createRef } from "react";
import { init, type EChartsType } from "echarts";

interface IProps {
  data: { label: string; current: number; average: number }[];
}

export default class Chart03 extends Component<IProps> {
  boxRef = createRef<HTMLDivElement>();
  ins: EChartsType | null = null;

  render() {
    return (
      <div ref={this.boxRef} style={{ width: "100%", height: "100%" }}></div>
    );
  }

  componentDidMount() {
    this.initChart();
  }

  componentDidUpdate(prevProps: Readonly<IProps>): void {
    // 控制只有 data 数据发现变化，才处理
    if (this.props.data === prevProps.data) {
      return;
    }

    const { data } = this.props;
    // 重新调用 this.ins.setOption
    this.ins?.setOption({
      xAxis: {
        data: data.map((item) => item.label),
      },
      series: [
        {
          data: data.map((item) => item.current),
        },
        {
          data: data.map((item) => item.average),
        },
      ],
    });
  }

  // 初始化
  initChart = () => {
    this.ins = init(this.boxRef.current);
    // 设置默认的配置
    this.ins.setOption({
      tooltip: {
        trigger: "axis",
      },
      legend: {
        right: 0,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: [],
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          name: "当月销售额",
          data: [],
          type: "line",
          areaStyle: {},
        },
        {
          name: "月均销售额",

          data: [],
          type: "line",
          areaStyle: {},
        },
      ],
    });
  };
}
